package com.dnjn.mes.biz.assist;

import com.dnjn.mes.biz.enums.DataType;
import com.dnjn.mes.biz.service.IMesRecordCapacityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Profile({"test", "dev", "local"})
@Slf4j
@Component
public class ScheduleMockDataAssist {

    @Autowired
    private IMesRecordCapacityService recordCapacityService;
    @Autowired
    RecordTaskHandler recordTaskHandler;

    @Scheduled(cron = "0 0/5 * * * ? ")
    public void handleExceptTask() {
        log.info("---- start mock capacity data---------------------------------");
        try {
            handleMockTask();
            //recordTaskHandler.handleBeat();
            //recordTaskHandler.handleCapacity();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private void handleMockTask() {
        LocalDateTime now = LocalDateTime.now();

//        int hour = now.toLocalTime().getHour();
//        boolean isA = hour >= 8 && hour < 20;
//        boolean isB = hour >= 20 || hour < 8;

        LocalDateTime startDatetime = LocalDateTime.of(now.toLocalDate(), LocalTime.of(8, 0));
//        if (isB) {
//            LocalDate dt = hour > 20 ? now.toLocalDate() : now.toLocalDate().plusDays(-1);
//            startDatetime = LocalDateTime.of(dt, LocalTime.of(20, 0));
//        }

        if (now.compareTo(startDatetime) <= 0) {
            startDatetime = startDatetime.plusDays(-1).withHour(20);//todo
        }

        long totalsec = Duration.between(startDatetime, now).toSeconds();

        int capacity = (int) RandomUtils.nextLong(totalsec / 66, totalsec / 40);

        recordTaskHandler.refreshRecordCapacity(capacity, LocalDateTime.now(), DataType.INT16);
    }

}
